package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.ExpTime;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.view.CustomView5;

//TODO  Progress设置为margin ，480和540的martop=15弄小点
public class PayNoCard extends BaseActivity_NoBar {
//	ImageView first;
	LinearLayout first;
	public static LinearLayout second;
	public static int height;   //一个验证码框框的高度
//	public static FrameLayout v;
	public static Context context;
	
	static RelativeLayout tip;
	static ImageView doHelp;
	
	public static final int JC = 12;
	
	public static LinearLayout progress;
	
	public static LinearLayout lin_yzm;
	public static TextView yzm;
	public static TextView help_code;  //帮助页面验证码
	public static TextView tv_sysm;   //帮助页面“使用说明”
	public static RelativeLayout top;
	public static LinearLayout ten;
	public static TextView exp_time;  //过期时间
	
	public static TextView tv_code_first;
	
	public static int h;  //比重  后验证码的高度
	
	public static DataLoader loader;
	
	static ProApplication applicaton;
	
	public static final int expireTime = 10;
	
	public static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				FrameLayout all = (FrameLayout) ((Activity) context)
						.findViewById(R.id.all);
				View a = ((Activity) context).findViewById(R.id.custom_view);
				// all.removeView(a);
				all.removeAllViews();
				View n = View.inflate(context, R.layout.activity_main_ok_3,
						null);
				// FrameLayout.LayoutParams fl = new
				// FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
				// FrameLayout.LayoutParams.FILL_PARENT);
				// fl.topMargin = 80;
				// n.setLayoutParams(fl);
				tip = (RelativeLayout) n.findViewById(R.id.tip);

				help_code = (TextView) n.findViewById(R.id.help_code);
				top = (RelativeLayout) n.findViewById(R.id.top);
				tv_sysm = (TextView) n.findViewById(R.id.tv_sysm);
				second = (LinearLayout) n.findViewById(R.id.second);
				ten = (LinearLayout) n.findViewById(R.id.ten);

				exp_time = (TextView) n.findViewById(R.id.exp_time);

				progress = (LinearLayout) n.findViewById(R.id.progress);
				progress.setVisibility(View.VISIBLE);
				yzm = (TextView) n.findViewById(R.id.yzm);
				yzm.setVisibility(View.GONE);

				// 使progress居中
				progress.setPadding(0, (height - h) / 2, 0, 0);

				// 上面的验证码居中
				LayoutParams lp_code = new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				lp_code.topMargin = (height - h) / 2;
				tv_code_first.setLayoutParams(lp_code);

				yzm.setLayoutParams(lp_code);

				lin_yzm = (LinearLayout) n.findViewById(R.id.lin_yzm);
				lin_yzm.setVisibility(View.GONE);

				tip.setVisibility(View.GONE);
				tip.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View view) {
						tip.setVisibility(View.GONE);
					}
				});

				doHelp = (ImageView) n.findViewById(R.id.doHelp);
				doHelp.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View view) {
						tip.setVisibility(View.VISIBLE);

						initHelp();
					}
				});

				LayoutParams lp = (LayoutParams) n.findViewById(R.id.first)
						.getLayoutParams();
				lp.topMargin = -height + JC;
				all.addView(n);

				getData();
				/*if (loader != null) {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					NameValuePair uID = new BasicNameValuePair("userId",
							SharePrefenceUtil.getUserID(context) + "");
					if(applicaton.locData != null && !((applicaton.locData.longitude + "").equals("4.9E"))) {
						NameValuePair longtitude = new BasicNameValuePair(
								"longitude", applicaton.locData.longitude + "");
						NameValuePair latitude = new BasicNameValuePair("latitude",
								applicaton.locData.latitude + "");
						params.add(uID);
						params.add(latitude);
						params.add(longtitude);
						loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.payNoCard,params, handler, "", false);
						CustomView5.fresh = false;
					} else {
						applicaton.startRequest(handler);
					}
				}*/

			} else if (msg.what == HttpTask.RESULT_OK) {
				CustomView5.fresh = true;
				String json = (String) msg.obj;
				System.err.println(json + "!!!!!!!!!!!!!!!!!!!!!!!!");

				if (json != null) {
					try {
						JSONObject jo = new JSONObject(json);
						if (StringUtils.isSuccess(json)) {
							progress.setVisibility(View.GONE);
							yzm.setVisibility(View.VISIBLE);
							lin_yzm.setVisibility(View.VISIBLE);

							Date date = new Date();
							long time = date.getTime();
							ExpTime et = new ExpTime();


							if (jo != null) {
								JSONObject jo_si = jo.optJSONObject("resultInfo");
								if(jo_si != null) {
									String code = jo_si.optString("randomCode");
									long hm_time = jo_si.optLong("remainingTime"); 
									ExpTime expTime = SharePrefenceUtil.getExpTime(context);
									if(code.trim().equals(expTime.getCode())) {
										setExpire(expTime);
									} else {
										handler.removeCallbacks(min_sj);
										handler.postDelayed(min_sj, 60000);
										exp_time.setText(R.string.expr_time);
										et.setTime(time - (600000 - hm_time));
//										et.setTime(time);
										et.setCode(code);
										SharePrefenceUtil.setExpTime(context, et);
										setExpire(et);
									}
									if(code.length() >= 4) {
										yzm.setText(code.substring(0, 4) + "  "
												+ code.substring(4, code.length()));
									}
								} else {
									//TODO  请求数据失败
									Toast.makeText(context, "网络错误,获取验证码失败", Toast.LENGTH_SHORT)
									.show();
								}
							}

						} else {
							if (jo != null) {
//								String randomCode = jo.optString("randomCode");
//								Toast.makeText(context, randomCode,
//										Toast.LENGTH_SHORT).show();
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

			} else if (msg.what == HttpTask.RESULT_ERROR) {
				CustomView5.fresh = true;
				Toast.makeText(context, "网络错误,获取验证码失败", Toast.LENGTH_SHORT)
						.show();
				fail();
			} else if(msg.what == ProApplication.location_cuccess) {
				CustomView5.fresh = false;
				if(applicaton.locData != null && !((applicaton.locData.longitude + "").equals("4.9E"))) {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					NameValuePair uID = new BasicNameValuePair("userId",
							SharePrefenceUtil.getUserID(context) + "");
					NameValuePair longtitude = new BasicNameValuePair(
							"longitude", applicaton.locData.longitude + "");
					NameValuePair latitude = new BasicNameValuePair("latitude",
							applicaton.locData.latitude + "");
					params.add(uID);
					params.add(latitude);
					params.add(longtitude);
					loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.payNoCard,params, handler, "", false);
				} else {
					Toast.makeText(context, "定位失败,暂不能获取验证码,请刷新", Toast.LENGTH_SHORT)
					.show();
					fail();
				}
			} else if(msg.what == ProApplication.location_fial) {
				CustomView5.fresh = true;
				Toast.makeText(context, "定位失败,暂不能获取验证码,请刷新", Toast.LENGTH_SHORT)
				.show();
				fail();
			}
			super.handleMessage(msg);
		}
		
	};
	
	public static void fail() {
		lin_yzm.setVisibility(View.VISIBLE);
		progress.setVisibility(View.GONE);
		ExpTime expTime = SharePrefenceUtil.getExpTime(context);
		String code = expTime.getCode();
		if(code.length() >= 4) {
			yzm.setText(code.substring(0, 4) + "  "
					+ code.substring(4, code.length()));
		}
		yzm.setVisibility(View.VISIBLE);
		
		setExpire(expTime);
	}
	
	 @Override
	protected void onDestroy() {
		 help_code_height = 0;
		 help_code_width = 0;
		 handler.removeCallbacks(min_sj);
		super.onDestroy();
	}

	static int s_height;  //分辨率高
	
//	static int minute; //过期剩余时间
	
	static Runnable min_sj = new Runnable() {
		@Override
		public void run() {
			ExpTime expTime = SharePrefenceUtil.getExpTime(context);
			setExpire(expTime);
			handler.postDelayed(min_sj, 60000);
		}
	};
	
	public static void setExpire(ExpTime expTime) {
        if(expTime.getTime() != 0l) {
        	Date newDate = new Date();
        	int minute = expireTime - (int) ((newDate.getTime() - expTime.getTime()) / (1000 * 60));
        	if(minute > 0) {
        		exp_time.setText(minute + "分钟后过期");
        		yzm.setTextColor(context.getResources().getColor(R.color.codeColor));
        	} else {
        		yzm.setTextColor(Color.RED);
        		exp_time.setText("支付码已过期");
        	}
        }
	}
	
	public static void getData() {
		if (loader != null) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair uID = new BasicNameValuePair("userId",
					SharePrefenceUtil.getUserID(context) + "");
			if(applicaton.locData != null && !((applicaton.locData.longitude + "").equals("4.9E"))) {
				NameValuePair longtitude = new BasicNameValuePair(
						"longitude", applicaton.locData.longitude + "");
				NameValuePair latitude = new BasicNameValuePair("latitude",
						applicaton.locData.latitude + "");
				params.add(uID);
				params.add(latitude);
				params.add(longtitude);
				loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.payNoCard,params, handler, "", false);
				CustomView5.fresh = false;
			} else {
				applicaton.startRequest(handler);
			}
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        context = this;
        setContentView(R.layout.activity_main_ok_3);
        applicaton = (ProApplication) getApplication();
        
        loader = new DataLoader(this);
        
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        s_height = dm.heightPixels;
        
//        v = (FrameLayout) getWindow().getDecorView().findViewById(android.R.id.content);
//        first = (ImageView) findViewById(R.id.first);
        first = (LinearLayout) findViewById(R.id.first);
        second = (LinearLayout) findViewById(R.id.second);
        yzm = (TextView) findViewById(R.id.yzm);
         
        help_code = (TextView) findViewById(R.id.help_code);  //帮助界面验证码展示
        tv_sysm = (TextView) findViewById(R.id.tv_sysm);      //帮助界面使用说明
        top = (RelativeLayout) findViewById(R.id.top);
        ten = (LinearLayout) findViewById(R.id.ten);
        lin_yzm = (LinearLayout) findViewById(R.id.lin_yzm);
        exp_time = (TextView) findViewById(R.id.exp_time);
        progress = (LinearLayout) findViewById(R.id.progress);
        
        //首先判断是否过期
        ExpTime expTime = SharePrefenceUtil.getExpTime(this);
        if(expTime.getTime() != 0l) {
        	Date newDate = new Date();
        	int minute = expireTime - (int) ((newDate.getTime() - expTime.getTime()) / (1000 * 60));
        	if(minute > 0) {
        		exp_time.setText(minute + "分钟后过期");
        		handler.postDelayed(min_sj, 60000);
        		yzm.setTextColor(getResources().getColor(R.color.codeColor));
        	} else {
        		exp_time.setText("支付码已过期");
        		yzm.setTextColor(Color.RED);
        	}
        } else {
//        	lin_yzm.setVisibility(View.GONE);
//        	progress.setVisibility(View.VISIBLE);
//        	getData();
        }
        if(expTime.getCode().length() >= 4) {
        	yzm.setText(expTime.getCode().substring(0, 4) + "  " + expTime.getCode().substring(4, expTime.getCode().length()));
        }
        
        tv_code_first = (TextView) findViewById(R.id.tv_code_first);
        
        tip = (RelativeLayout) findViewById(R.id.tip);
        tip.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				tip.setVisibility(View.GONE);
			}
		});
        
        doHelp = (ImageView) findViewById(R.id.doHelp);
        doHelp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				tip.setVisibility(View.VISIBLE);
				
				initHelp();
			}
		});
        
    }
    
    public void exit(View view) {
    	finish();
    }

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(hasFocus) {
			height= first.getHeight();  
			LayoutParams lp = (LayoutParams) first.getLayoutParams();
			lp.topMargin = -height + JC;  //12消除锯齿
//			height = 183;
			Log.i("aaa", height + "gaooooooooooooooooooooooooooo");
			
			handler.post(new Runnable() {
				@Override
				public void run() {
					initHelp();
					if(SharePrefenceUtil.getTip(context)) {
						tip.setVisibility(View.VISIBLE);
						SharePrefenceUtil.setTip(context);
						
						lin_yzm.setVisibility(View.GONE);
			        	progress.setVisibility(View.VISIBLE);
			        	getData();
						
					}
					
					/*Rect r_second = new Rect();
					second.getGlobalVisibleRect(r_second);
					int y_height = yzm.getHeight() / 2;
					int s = (r_second.bottom - r_second.top - et_height) / 2;
					int total_halfHeight = (r_second.bottom - r_second.top) / 2;
					int m_top = total_halfHeight - y_height;*/
					
					h = lin_yzm.getHeight();
					System.out.println(h + "hhhhhhhhhhhhhhhhh");
					LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
					lp.topMargin = (height - h) / 2;
					yzm.setLayoutParams(lp);
					
					tv_code_first.setLayoutParams(lp);
				}
			});
//			tip.setVisibility(View.VISIBLE);
//			initHelp();
		}
		super.onWindowFocusChanged(hasFocus);
	}
    
	static int help_code_height;
	static int help_code_width;
	static int margin_top;
	static int margin_left;
    public static void initHelp() {
    	int tv_height = 20;  //帮助的验证码上间距
    	int tv_left_right = 40;  //帮助的验证码的左右间距
    	if(s_height <= 960) {
    		tv_height = 15;
    	}
    	
    	Rect rect = new Rect(); 
	    Window win = ((Activity) context).getWindow(); 
	    win.getDecorView().getWindowVisibleDisplayFrame(rect); 
	    int statusBarHeight = rect.top;
		
		
		//使用说明
		int sysm_top = top.getHeight();
		android.widget.RelativeLayout.LayoutParams sysmlp = new android.widget.RelativeLayout.LayoutParams(android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
		sysmlp.topMargin = sysm_top;
		sysmlp.addRule(RelativeLayout.CENTER_HORIZONTAL);
		tv_sysm.setLayoutParams(sysmlp);
		
		Rect r_second = new Rect();
		second.getGlobalVisibleRect(r_second);
		
		//验证码
				Rect r = new Rect();
				yzm.getGlobalVisibleRect(r);
				if(help_code_width != 0 && help_code_height != 0) {
				} else {
					margin_left = r.left + tv_left_right;
					help_code_height = r.bottom - r.top + tv_height * 2;
					int half = (r_second.bottom - r_second.top - help_code_height) / 2;
					margin_top = r_second.top + half - statusBarHeight;
					int margin_right = r.right - tv_left_right;
					help_code_width = margin_right - margin_left;
				}
				android.widget.RelativeLayout.LayoutParams bzlp = new android.widget.RelativeLayout.LayoutParams(help_code_width,help_code_height);
				bzlp.leftMargin = margin_left;
		
		
		int ten_margintop = r_second.bottom - statusBarHeight + 10;
		android.widget.RelativeLayout.LayoutParams tenlp = new android.widget.RelativeLayout.LayoutParams(android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
		tenlp.topMargin = ten_margintop;
		tenlp.leftMargin = margin_left;
		ten.setLayoutParams(tenlp);
		
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		bzlp.topMargin = margin_top;
		help_code.setLayoutParams(bzlp);
    }
}
